package Servlets;

import Negocio.AdminDB;
import Negocio.Cita;
import Negocio.CitaPendiente;
import Negocio.MessageLogger;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author asabido
 */
public class ListadoCitas extends BaseServlet {

  RequestDispatcher rd;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
    */

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException
        {

        HttpSession s = request.getSession(true);
        Cookie[] cookies = request.getCookies();
        MessageLogger ml = new MessageLogger(getServletContext());
        boolean login = false;
        
        for(int i=0; i<cookies.length; i++) {
          Cookie cookie = cookies[i];
          if (cookie.getName().equals("login") && cookie.getValue().equals("true"))
            login=true;
        }
      
        
        if(login){
            AdminDB adb = new AdminDB();
            CitaPendiente cp = new CitaPendiente();
            Cita c = new Cita();
            List<CitaPendiente> citasPendientes = null;
            List<Cita> citas = null;
            boolean valid=false;       
            
            String boton = request.getParameter("eliminar");
            if(boton==null) boton = request.getParameter("adjudicar");
            if(boton==null) boton = request.getParameter("cancelar");
            if(boton==null) boton = request.getParameter("modificar");
            
            if(boton!=null)
            {
                if(boton.equalsIgnoreCase("Adjudicar")){
                    try {
                        int fp = Integer.parseInt(request.getParameter("idPeticion"));
                        cp.getByID(adb.getConnection(),fp);
                        valid = cp.adjudicar(); 
                    } catch (SQLException ex) {
                        Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                    }

                    if(valid){
                       ml.log("'Admin' - cita ("+cp.getFechahora()+") del cliente ("+cp.getEmailCliente()+") adjudicada");
                        try {
                            citasPendientes = cp.getAllCitas(adb.getConnection());
                            citas = c.getAll(adb.getConnection());

                            s.setAttribute("listaDeCitasPendientes", citasPendientes);
                            s.setAttribute("listaDeCitas", citas);
                        } catch (SQLException ex) {
                            Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                        }
                       dispatch("/listaCitas.jsp", request, response);
                    } else {
                        dispatch("/clienteNoExiste.jsp", request, response);
                        ml.log("'Admin' - fallo adjudicando la cita ("+cp.getFechahora()+"), el cliente ("+cp.getEmailCliente()+") no existe");
                    }
                }
                else if (boton.equalsIgnoreCase("Eliminar")){
                    try {
                        int fp = Integer.parseInt(request.getParameter("idPeticion"));
                        cp.getByID(adb.getConnection(),fp);
                        valid = cp.borrar(); 
                    } catch (SQLException ex) {
                        Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                    }

                    if(valid){
                        try {
                            citasPendientes = cp.getAllCitas(adb.getConnection());
                            citas = c.getAll(adb.getConnection());

                            s.setAttribute("listaDeCitasPendientes", citasPendientes);
                            s.setAttribute("listaDeCitas", citas);
                        } catch (SQLException ex) {
                            Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                        }
                       ml.log("'Admin' - cita ("+cp.getFechahora()+") del cliente ("+cp.getEmailCliente()+") eliminada");
                       dispatch("/listaCitas.jsp", request, response);
                    } else {
                        dispatch("/404.jsp", request, response);
                        ml.log("'Admin' - fallo eliminando la cita ("+cp.getFechahora()+") del cliente ("+cp.getEmailCliente()+")");
                    }
                }
                else if (boton.equalsIgnoreCase("Cancelar")){
                    try {
                        int ca = Integer.parseInt(request.getParameter("idCitaAdjudicada"));
                        c.getByID(adb.getConnection(), ca);
                        valid = c.borrar(); 
                    } catch (SQLException ex) {
                        Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                    }

                    if(valid){
                        try {
                            citasPendientes = cp.getAllCitas(adb.getConnection());
                            citas = c.getAll(adb.getConnection());

                            s.setAttribute("listaDeCitasPendientes", citasPendientes);
                            s.setAttribute("listaDeCitas", citas);
                        } catch (SQLException ex) {
                            Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                        }
                        ml.log("'Admin' - cita ("+c.getFecha()+" "+c.getHora()+") del cliente ("+c.getCliente().getEmail()+") cancelada");
                       dispatch("/listaCitas.jsp", request, response);
                    } else {
                        ml.log("'Admin' - fallo cancelando cita ("+c.getFecha()+" "+c.getHora()+") del cliente ("+c.getCliente().getEmail()+"), cita facturada pendiente de cobro");
                        dispatch("/citaNoFacturada.jsp", request, response);
                    }
                }
                else if (boton.equalsIgnoreCase("Modificar")){
                    try {
                        int ca = Integer.parseInt(request.getParameter("idCitaAdjudicada"));
                        c.getByID(adb.getConnection(), ca);
                        s.setAttribute("Cita", c);
                        ml.log("'Admin' - cita ("+c.getFecha()+" "+c.getHora()+") del cliente ("+c.getCliente().getEmail()+") modificandose");
                        dispatch("/modificarCita.jsp", request, response);
                    } catch (SQLException ex) {
                        Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                        ml.log("'Admin' - fallo modificando la cita ("+c.getFecha()+" "+c.getHora()+") del cliente ("+c.getCliente().getEmail()+")");
                        dispatch("/404.jsp", request, response);
                    }
                }
            }
            else{
                try {
                        citasPendientes = cp.getAllCitas(adb.getConnection());
                        citas = c.getAll(adb.getConnection());
                        s.setAttribute("listaDeCitasPendientes", citasPendientes);
                        s.setAttribute("listaDeCitas", citas);
                    } catch (SQLException ex) {
                        Logger.getLogger("ListadoCitas").log(Level.SEVERE, null, ex);
                    }
                    ml.log("'Admin' - listado de citas");
                   dispatch("/listaCitas.jsp", request, response);
            }
        }
        else dispatch("/index.jsp", request, response);
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ListadoCitas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ListadoCitas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
